package com.company.OfferGuide;

import com.company.TreeNode;

import java.util.*;

public class 从上到下打印二叉树3 {


    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> lists = new ArrayList<>();
        if (root == null) return lists;
        boolean flag = true;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        List<Integer> list = new ArrayList<>();
        int thisNodeCount = 1,nodeCount = 0,preNodeCount = 0;
        while (!queue.isEmpty()){
            TreeNode treeNode = queue.poll();
            nodeCount++;

            if (treeNode.left != null) {
                preNodeCount++;
                queue.offer(treeNode.left);
            }
            if (treeNode.right != null) {
                preNodeCount++;
                queue.offer(treeNode.right);
            }

            if (nodeCount == thisNodeCount) {
                nodeCount = 0;
                thisNodeCount = preNodeCount;
                preNodeCount = 0;
                if (!flag) {
                    Collections.reverse(list);
                }
                lists.add(list);
                list = new ArrayList<>();
                flag = !flag;

            }
        }

        return lists;
    }

}
